package com.shadowlight.hero_story.cmdHandler;

import com.shadowlight.hero_story.Broadcaster;
import com.shadowlight.hero_story.pojo.UserRepository;
import com.shadowlight.hero_story.pojo.MoveState;
import com.shadowlight.hero_story.pojo.User;
import com.shadowlight.hero_story.msg.GameMsgProtocol;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;

/**
 * @Description 用户移动处理器
 * @Author cz
 * @Date 2022/3/2
 */
public class UserMoveToCmdHandler implements ICmdHandler<GameMsgProtocol.UserMoveToCmd> {

    @Override
    public void handle(ChannelHandlerContext channelHandlerContext, GameMsgProtocol.UserMoveToCmd msg) {
        Integer id = (Integer) channelHandlerContext.channel().attr(AttributeKey.valueOf("userId")).get();
        if (id == null) return;

        //存储一下用户的移动状态
        User user = UserRepository.getInstance().getUserById(id);
        if (user == null) return;

        user.setMoveState(new MoveState(msg.getMoveFromPosX(), msg.getMoveFromPosY(), msg.getMoveToPosX(), msg.getMoveToPosY(), System.currentTimeMillis()));
        UserRepository.getInstance().save(user);

        GameMsgProtocol.UserMoveToResult.Builder userMoveToResultBuilder = GameMsgProtocol.UserMoveToResult.newBuilder();
        userMoveToResultBuilder.setMoveUserId(id);
        userMoveToResultBuilder.setMoveFromPosX(user.getMoveState().getMoveFromPosX());
        userMoveToResultBuilder.setMoveFromPosY(user.getMoveState().getMoveFromPosY());
        userMoveToResultBuilder.setMoveToPosX(user.getMoveState().getMoveToPosX());
        userMoveToResultBuilder.setMoveToPosY(user.getMoveState().getMoveToPosY());
        userMoveToResultBuilder.setMoveStartTime(user.getMoveState().getStartTime());
        Broadcaster.broadcast(userMoveToResultBuilder.build());
    }
}
